<?php

namespace app\common\library\job;

use app\common\library\TeamCount;
use think\Log;
use think\queue\Job;

class TeamCountJob
{

    /**
     * fire方法是消息队列默认调用的方法
     * @param Job            $job      当前的任务对象
     * @param array|mixed    $data     发布任务时自定义的数据
     */
    public function fire(Job $job, $data)
    {
        Log::write(var_export($data, true), "TeamCountJob", true);

        $isJobDone = $this->doJob($data);
        if ($isJobDone) {
            // 如果任务执行成功， 记得删除任务
            $job->delete();
        } else {
            if ($job->attempts() > 3) {

                $job->delete();

                // 也可以重新发布这个任务
                //print("<info>Hello Job will be availabe again after 2s."."</info>\n");
                //$job->release(2); //$delay为延迟时间，表示该任务延迟2秒后再执行
            }
        }
    }

    /**
     * 根据消息中的数据进行实际的业务处理...
     */
    private function doJob($data)
    {
        $user_array = [];
        $user_id = $data["user_id"] ?? 0;
        if ($user_id) {
            $user_ids = [$user_id];
            $user_array = TeamCount::getTreeRelations($user_ids, $user_array);
            $team_count = count($user_array);
            Log::write("查到用户ID:" . $user_id . "的网体人数:" . $team_count, "TeamCountJobResult", true);

            db("user")->where("id", $user_id)->update(["team_count" => $team_count]);
        }
        return true;
    }
}
